<template>
  <div v-if="props.readonly && props.readonly == 1">{{ name_format }}</div>
  <el-select
    v-else
    collapse-tags
    collapse-tags-tooltip
    :max-collapse-tags="1"
    v-model="name"
    @focus="focus"
    :placeholder="props.placeholder || '请选择'"
    clearable
    filterable
    :multiple="props.multiple == 1"
  >
    <el-option
      v-for="item in options"
      :key="item.dict_code"
      :label="item.dict_label"
      :value="val_format(item)"
    />
  </el-select>
</template>

<script setup lang="ts">
const { proxy } = getCurrentInstance();
//counter
import useCounterStore from "@/store/counter";
const counter = useCounterStore();

let props = defineProps([
  "modelValue",
  "dictCode",
  "val",
  "multiple",
  "placeholder",
  "readonly",
]);
const emit = defineEmits(["update:modelValue", "fatherMethods"]);

let options = ref([]);

onMounted(() => {
  getInfo();
});

let name_format = computed(() => {
  let current;
  for (let index = 0; index < options.value.length; index++) {
    const element = options.value[index];
    if (element.dict_code == props.modelValue) current = index;
  }
  return current >= 0 ? options.value[current].dict_label : "-";
});

const name = computed({
  get() {
    return props.modelValue;
  },
  set(value: String) {
    emit("update:modelValue", value);
    emit("fatherMethods");
  },
});

function val_format(item) {
  return props.val ? item[props.val] : item.dict_code;
}

async function getInfo() {
  if (counter.dictOptions.hasOwnProperty(props.dictCode)) {
    options.value = counter.dictOptions[props.dictCode];
  } else {
    let { rows } = await proxy.$apis.dict({
      type: "list",
      data: { code: props.dictCode },
    });
    counter.dictOptions[props.dictCode] = rows[0].data;
    options.value = rows[0].data;
  }
}

function focus() {
  if (!options.value.length) getInfo();
}
</script>

<style lang="scss" scoped>
.container {
}
</style>
